package cn.shanke.torrentmanagerserver.controller;

import cn.shanke.torrentmanagerserver.controller.common.ResponseModel;
import cn.shanke.torrentmanagerserver.core.AuthTool;
import cn.shanke.torrentmanagerserver.model.Config;
import cn.shanke.torrentmanagerserver.service.ConfigService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private ConfigService configService;

    @GetMapping("/check")
    public ResponseModel checkAuth() {
        return ResponseModel.success().data("Welcome to TorrentManager!");
    }

    @PostMapping("/doAuth")
    public ResponseModel doAuth(@RequestBody JSONObject request) {
        String passkey = request.getString("passkey");
        String passkeyReal = configService.getCurrent().getPasskey();
        if (!passkeyReal.equals(passkey)) {
            return ResponseModel.failure("密码错误");
        }
        return ResponseModel.success().data(AuthTool.genToken(passkey));
    }

    @PostMapping("/resetPasskey")
    public ResponseModel resetPasskey(@RequestBody JSONObject request) {
        String oldPass = request.getString("oldPass");
        String newPass = request.getString("newPass");
        if (StringUtils.hasText(oldPass) || StringUtils.hasText(newPass)) {
            return ResponseModel.failure("参数错误");
        }
        String passkeyReal = configService.getCurrent().getPasskey();
        if (!passkeyReal.equals(oldPass)) {
            return ResponseModel.failure("原密码错误");
        }
        Config config = configService.getCurrent();
        config.setPasskey(newPass);
        configService.updateById(config);
        return ResponseModel.success().data(AuthTool.genToken(newPass));
    }

    @GetMapping("/fail")
    public ResponseModel authFailed() {
        return ResponseModel.model(ResponseModel.CODE_NO_AUTH,"认证失败");
    }
}
